package com.dayang.filter;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.dayang.model.Userif;
import com.dayang.service.UserService;

public class OAuth2Realm extends AuthorizingRealm{
	
	@Resource
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		 // 根据用户配置用户与权限  
        if (principals == null) {  
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");  
        }  
        String username = (String)principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //暂时不加权限
        return authorizationInfo; 
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		  UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
	        // 简单默认一个用户,实际项目应User user = userService.getByAccount(token.getUsername());  
		  List<Userif> users= userService.findByUsername(token.getUsername());
	        //User user = new User("shiro", "123456");  
	        if (users == null ||users.size() == 0) {  
	        	return null;   
	        }  
	        SimpleAuthenticationInfo info = null;  
	        if (users!=null && users.get(0).getUsername().equals(token.getUsername())) {  
	            info = new SimpleAuthenticationInfo(users.get(0).getUsername(), users.get(0).getPassword(), getName());  
	        }  
	        return info;  
	}

}
